<?php
declare (strict_types=1);

namespace app\common\model;

use ffhome\frame\model\BaseModel;
use ffhome\frame\util\CacheUtil;
use think\facade\Db;

class TallyCustom extends BaseModel
{
    const MODEL_NAME = 'tally_custom';

    public static function getList()
    {
        return CacheUtil::get("custom_list", function () {
            return Db::name(self::MODEL_NAME)->alias('c')
                ->leftJoin(AclUser::MODEL_NAME . ' a', "a.id=c.accounting_id")
                ->field('c.id,c.accounting_id,c.number,c.name,c.estimate_time,concat(a.username,a.nickname) accounting_name')
                ->where([['c.status', '=', self::ENABLE],])->order('c.number')->select()->toArray();
        }, self::MODEL_NAME);
    }

    public static function getListByAccountingId($accountingId)
    {
        return CacheUtil::get("custom_list_accounting_id_{$accountingId}", function () use ($accountingId) {
            return Db::name(self::MODEL_NAME)->alias('c')
                ->leftJoin(AclUser::MODEL_NAME . ' a', "a.id=c.accounting_id")
                ->field('c.id,c.accounting_id,c.number,c.name,c.estimate_time,concat(a.username,a.nickname) accounting_name')
                ->where([['c.status', '=', self::ENABLE], ['c.accounting_id', '=', $accountingId],])->order('c.number')
                ->select()->toArray();
        }, self::MODEL_NAME);
    }

    public static function getMyList()
    {
        if (auth('roleAccounting')) {
            return self::getListByAccountingId(currentUserId());
        }
        return self::getList();
    }

    public static function getAccountingIdById($id)
    {
        $custom = Db::name(self::MODEL_NAME)->find($id);
        if (empty($custom)) return 0;
        return $custom['accounting_id'];
    }
}